﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;

namespace Chenglin.W8Timer
{
    internal class SuspensionManager
    {
        private static Dictionary<string, object> s_sessionState = new Dictionary<string, object>();
        private static List<Type> s_knownTypes = new List<Type>();
        private const string s_stateFileName = "_sessionState.xml";

        /// <summary>
        /// Get the current session state.
        /// </summary>
        public static Dictionary<string, object> SessionState
        {
            get { return s_sessionState; }
        }

        /// <summary>
        /// Allows custom types to be added to the list of types that can be serialized
        /// </summary>
        public static List<Type> KnownTypes
        {
            get { return s_knownTypes; }
        }

        /// <summary>
        /// Save the current session state.
        /// </summary>
        public static async Task SaveAsync()
        {
            // Get the output stream for the SessionState file.
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(s_stateFileName, CreationCollisionOption.ReplaceExisting);
            using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
            {
                // Serialize the Session State.
                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), s_knownTypes);
                serializer.WriteObject(transaction.Stream.AsStreamForWrite(), s_sessionState);

                await transaction.CommitAsync();
            }
        }

        /// <summary>
        /// Restore the saved session state.
        /// </summary>
        public static async Task RestoreAsync()
        {
            try
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(s_stateFileName);
                if (file == null)
                    return;

                using (IInputStream inStream = await file.OpenSequentialReadAsync())
                {
                    // Deserialize the Session State.
                    DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), s_knownTypes);

                    s_sessionState = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
                }
            }
            catch (Exception)
            {
                // Restoring state is best-effort. 
                // If it fails, the app will just come up with a new session.
                //
            }
        }
    }
}
